<template>
  <div class="picture-list">
    <!-- 瀑布流开始 -->
    <template v-if="dataList.length > 0">
      <Waterfall
        :list="dataList"
        :width="320"
        img-selector="url"
        row-key="id"
        @afterRender="onAfterRender"
      >
        <template #default="{ item, url, index }">
          <!-- 每一项具体内容 -->
          <a-card hoverable style="margin-bottom: 12px" @click="doClickPicture(item)">
            <template #cover>
              <!-- 优化图片加载 -->
              <div class="image-container">
                <LazyImg :alt="item.name" :loading="loading" :url="url" decoding="async" />
                <div class="image-overlay">
                  <h3 class="image-title">{{ item.name }}</h3>
                  <a-flex class="image-tags">
                    <a-tag color="green">
                      {{ item.category ?? '默认' }}
                    </a-tag>
                    <a-tag v-for="tag in item.tags" :key="tag">
                      {{ tag }}
                    </a-tag>
                  </a-flex>
                  <!-- 将操作按钮移到overlay中 -->
                  <div v-if="showOp" class="image-actions">
                    <a-button type="text" @click.stop="(e) => doShare(item, e)">
                      <template #icon><ShareAltOutlined style="color: #fff" /></template>
                    </a-button>
                    <a-button type="text" @click.stop="(e) => doSearch(item, e)">
                      <template #icon><SearchOutlined style="color: #fff" /></template>
                    </a-button>
                    <a-button type="text" @click.stop="(e) => doEdit(item, e)">
                      <template #icon><EditOutlined style="color: #fff" /></template>
                    </a-button>
                    <a-button type="text" @click.stop="(e) => doDelete(item, e)">
                      <template #icon><DeleteOutlined style="color: #fff" /></template>
                    </a-button>
                  </div>
                </div>
              </div>
            </template>
          </a-card>
        </template>
      </Waterfall>
    </template>

    <!-- 空状态 -->
    <a-empty v-else-if="!loading" description="暂无数据" />

    <!-- 修改加载更多部分，添加 ref -->
    <div v-if="loading || hasMore" ref="loadingRef" class="loading-more">
      <a-spin v-if="loading" />
      <span v-else>加载更多...</span>
    </div>

    <!-- 分享弹窗 -->
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import {
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { deletePictureUsingPost } from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import ShareModal from '@/components/ShareModal.vue'
import { onMounted, onUnmounted, ref } from 'vue'
import { LazyImg, Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'

interface Props {
  dataList: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  hasMore?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
  hasMore: false,
})

const emit = defineEmits(['loadMore'])

const router = useRouter()

// 滚动加载相关
let isLoadingMore = false

// 添加节流函数
const throttle = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null
  let lastTime = 0

  return function (this: any, ...args: any[]) {
    const now = Date.now()

    if (lastTime && now < lastTime + delay) {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        lastTime = now
        fn.apply(this, args)
      }, delay)
    } else {
      lastTime = now
      fn.apply(this, args)
    }
  }
}

// 优化滚动检测
const checkScrollBottom = throttle(() => {
  if (isLoadingMore || !props.hasMore || props.loading) return

  // 使用 IntersectionObserver 替代滚动监听
  const scrollHeight = document.documentElement.scrollHeight
  const scrollTop = document.documentElement.scrollTop
  const clientHeight = document.documentElement.clientHeight

  if (scrollHeight - scrollTop - clientHeight < 100) {
    isLoadingMore = true
    emit('loadMore')
  }
}, 200) // 200ms 的节流时间

// 使用 IntersectionObserver 优化滚动检测
const loadingRef = ref<HTMLElement>()
let observer: IntersectionObserver | null = null

// 瀑布流渲染完成后允许继续加载
const onAfterRender = () => {
  isLoadingMore = false
}

onMounted(() => {
  // 优先使用 IntersectionObserver
  if ('IntersectionObserver' in window && loadingRef.value) {
    observer = new IntersectionObserver(
      (entries) => {
        const target = entries[0]
        if (target.isIntersecting && !isLoadingMore && !props.loading && props.hasMore) {
          emit('loadMore')
        }
      },
      {
        root: null,
        rootMargin: '100px',
        threshold: 0,
      },
    )

    observer.observe(loadingRef.value)
  } else {
    // 降级使用滚动监听
    window.addEventListener('scroll', checkScrollBottom)
  }
})

onUnmounted(() => {
  if (observer) {
    observer.disconnect()
  } else {
    window.removeEventListener('scroll', checkScrollBottom)
  }
})

// 跳转至图片详情页
const doClickPicture = (picture: API.PictureVO) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}

// 搜索
const doSearch = (picture, e) => {
  e.stopPropagation() // 阻止冒泡
  window.open(`/search_picture?pictureId=${picture.id}`)
}

// 编辑
const doEdit = (picture, e) => {
  e.stopPropagation() // 阻止冒泡
  router.push({
    path: '/add_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除
const doDelete = async (picture, e) => {
  e.stopPropagation() // 阻止冒泡
  const id = picture.id
  if (!id) return
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    props.onReload?.()
  } else {
    message.error('删除失败')
  }
}

// 分享相关
const shareModalRef = ref()
const shareLink = ref<string>()
const doShare = (picture, e) => {
  e.stopPropagation() // 阻止冒泡
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}
</script>

<style scoped>
.picture-list {
  position: relative;
  min-height: 200px;
}

.loading-more {
  text-align: center;
  padding: 20px 0;
}

/* 添加空状态样式 */
:deep(.ant-empty) {
  margin: 32px 0;
}

/* 添加图片占位样式 */
:deep(.lazy-img-loading) {
  background: #f0f2f5;
  min-height: 200px;
}

/* 添加图片渐变动画 */
:deep(.lazy-img) {
  transition: opacity 0.3s;
}

:deep(.lazy-img[loading]) {
  opacity: 0;
}

:deep(.lazy-img:not([loading])) {
  opacity: 1;
}

.image-container {
  position: relative;
  overflow: hidden;
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4), transparent);
  padding: 20px 16px;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.image-container:hover .image-overlay {
  transform: translateY(0);
}

.image-title {
  color: #fff;
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.image-tags {
  gap: 8px;
  flex-wrap: wrap;
}

.image-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 4px;
}

:deep(.image-actions .ant-btn) {
  padding: 4px 8px;
  height: auto;

  &:hover {
    background: rgba(255, 255, 255, 0.1);
  }
}

/* 移除原有卡片动作样式 */
:deep(.ant-card-actions) {
  display: none;
}

:deep(.ant-card-body) {
  display: none;
}

:deep(.ant-card) {
  background: transparent;
}
</style>
